import { getEnv, getAllEnv, validateEnv, printEnvInfo, isProduction, isDevelopment, isStaging } from '../utils/env';
import { databaseConfig, validateDatabaseConfig } from './database';

// 应用配置接口
export interface AppConfig {
  port: number;
  env: string;
  debug: boolean;
  cors: {
    origin: string | string[];
    credentials: boolean;
  };
  logLevel: string;
  apiRateLimit: number;
  sessionSecret: string;
  redisUrl?: string;
  sslEnabled: boolean;
  compressionEnabled: boolean;
}

// 从环境变量读取应用配置
export const appConfig: AppConfig = {
  port: getEnv('PORT'),
  env: getEnv('NODE_ENV'),
  debug: getEnv('DEBUG'),
  cors: {
    origin: getEnv('CORS_ORIGIN'),
    credentials: getEnv('CORS_CREDENTIALS')
  },
  logLevel: getEnv('LOG_LEVEL'),
  apiRateLimit: getEnv('API_RATE_LIMIT'),
  sessionSecret: getEnv('SESSION_SECRET'),
  redisUrl: getEnv('REDIS_URL'),
  sslEnabled: getEnv('SSL_ENABLED'),
  compressionEnabled: getEnv('COMPRESSION_ENABLED')
};

// 导出数据库配置
export { databaseConfig, validateDatabaseConfig, getDatabaseUrl } from './database';
export type { DatabaseConfig } from './database';

// 导出环境变量相关
export { 
  getEnv, 
  getAllEnv, 
  validateEnv, 
  printEnvInfo, 
  isProduction, 
  isDevelopment, 
  isStaging 
} from '../utils/env';

// 验证所有配置
export function validateConfig(): boolean {
  const envValidation = validateEnv();
  if (!envValidation.isValid) {
    console.error('环境变量验证失败:');
    envValidation.errors.forEach(error => console.error(`  - ${error}`));
    return false;
  }
  
  if (!validateDatabaseConfig()) {
    return false;
  }
  
  if (appConfig.port < 1 || appConfig.port > 65535) {
    console.error('应用配置错误: 端口号必须在 1-65535 之间');
    return false;
  }

  if (!appConfig.sessionSecret || appConfig.sessionSecret === 'default-secret-key') {
    console.warn('警告: 使用默认会话密钥，生产环境请设置 SESSION_SECRET');
  }

  if (appConfig.env === 'production' && appConfig.debug) {
    console.warn('警告: 生产环境启用了调试模式');
  }
  
  return true;
}

// 打印配置信息（仅开发环境）
export function printConfig(): void {
  if (isDevelopment()) {
    printEnvInfo();
    console.log('=== 数据库配置 ===');
    console.log(`主机: ${databaseConfig.host}:${databaseConfig.port}`);
    console.log(`数据库: ${databaseConfig.database}`);
    console.log(`用户名: ${databaseConfig.username}`);
    console.log(`方言: ${databaseConfig.dialect}`);
    console.log(`连接池: ${databaseConfig.pool?.max || 'default'} 最大连接`);
  }
} 